package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author zh
 * @date 2025/9/2
 * @description 监听用户注册信息
 */
@Component
@Slf4j
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;

    /*
    根据实现类中的内容确定交换机和队列
    //在此需要给当前注册的用户进行初始化赋值:同步/异步:mq发送消息
	rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());
     */
    //用户注册成功
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            exchange =@Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void userRegister(Long userId, Message message, Channel channel){
        System.out.println("用户注册成功,用户id:"+userId);
        try {
            if (null != userId){
                //此时说明获取到了用户id,调用服务层的方法
                userAccountService.userRegister(userId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            //可采用Redis进行重试
            //如果是网络波动的原因,可以调用内置的重试方法channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //如果数据特别重要,重试多次仍然失败,可以落盘数据到数据库表,存储信息
            /*
            if(count>=3){
                落地数据库,存储信息
            }
            */
        }
        //手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);//false不批量处理
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
